package com.ghw.neteasemusic.common.handler;


import com.ghw.neteasemusic.common.exceptions.JwtInvalidException;
import com.ghw.neteasemusic.common.exceptions.ServiceException;
import com.ghw.neteasemusic.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常捕获
 *
 * @author violet
 * @since 2021/11/28 0:08
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public R<Boolean> baseEx(ServiceException e) {
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(JwtInvalidException.class)
    public R<Boolean> jwtEx(JwtInvalidException e) {
        log.error("jwt error: ", e);
        return R.fail("登录信息已失效，请重新登录");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> methodArgumentNotValidaException(MethodArgumentNotValidException e) {
        return R.fail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public R<Boolean> runtimeEx(RuntimeException e) {
        log.error("runtime error: ", e);
        return R.fail("系统错误");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public R<Boolean> illegalArgsEx(IllegalArgumentException e) {
        log.error("args error: ", e);
        return R.fail("参数不正确");
    }

    @ExceptionHandler(Exception.class)
    public R<Boolean> ex(Exception e) {
        log.error("system error: ", e);
        return R.fail("系统错误");
    }

}
